package com.example.activelifecycletest.network.json;

import android.os.Bundle;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * jsonObject
 * @author zhangding
 * @date 2022年5月8日20:28:10
 */
public class JsonObjectActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sendRequestWithOkhttp();
    }

    /**
     * 发送http请求
     */
    private void sendRequestWithOkhttp(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    OkHttpClient client = new OkHttpClient();
                    /**
                     * 模拟器会将127.0.0.1识别为模拟器本身
                     * 因此需要使用192.168.10.7局域网ip或者10.0.2.2去访问模拟器本身的主机
                     */
                    Request request = new Request.Builder()
                                        .url("http://192.168.10.7/android_data.json")
                                        .build();
                    Response response = client.newCall(request).execute();
                    String responseData = response.body().string();
                    parseJSONWithJSONObject(responseData);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();

    }

    /**
     * 返回json串解析
     * @param jsonData
     */
    private void parseJSONWithJSONObject(String jsonData){
        try {
            JSONArray jsonArray = new JSONArray(jsonData);
            for (int index = 0; index < jsonArray.length(); index++){
                JSONObject jsonObject = jsonArray.getJSONObject(index);
                String id = jsonObject.getString("id");
                String name = jsonObject.getString("name");
                String version = jsonObject.getString("version");
                Log.d("zhang","id :" + id);
                Log.d("zhang","name :" + name);
                Log.d("zhang","version :" + version);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
